from django import http
from django.shortcuts import render
from django_redis import get_redis_connection
# Create your views here.
from django.views import View

from apps.verifications import constants
import random

from utils.response_code import RETCODE


class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 生成图片验证码
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()

        image_client = get_redis_connection('verify_image_code')

        image_client.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        return http.HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 1.接收参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2.校验正则
        # 3.对比图形验证码
        # 3.1链接数据库
        image_client = get_redis_connection('verify_image_code')
        # 3.2取出redis中的图形验证码
        redis_img_code = image_client.get('img_%s' % uuid)
        if not redis_img_code:
            return http.JsonResponse({'code': "4001", 'errmsg': '图形验证码失效了'})

        # 3.3删除图形验证码
        image_client.delete('img_%s' % uuid)

        # 3.4和前端的值进行判断对比
        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})
        # 4.生成随机六位码
        sms_code = "%06d" % random.randint(0, 999999)
        # 5.保存redis sms_code
        redis_sms_client = get_redis_connection('sms_code')
        send_flag = redis_sms_client.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
        # 1.创建管道
        p1 = redis_sms_client.pipeline()
        # 2.添加任务
        p1.setex('sms_%s' % mobile, 300, sms_code)
        p1.setex('send_flag_%s' % mobile, 60, 1)
        # 3.执行
        p1.execute()
        # 6.发短信
        from celery_tasks.sms.tasks import send_sms_code_ccp
        send_sms_code_ccp.delay(mobile, sms_code)
        print("原始文件短信码", sms_code)
        # 7.返回响应
        return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功'})
